package ivr

import (
	"errors"
	"gitee.com/zackeus/go-boot/freeswitch/mod/xmlcurl"
	"github.com/beevik/etree"
)

type (
	Xml struct {
		doc   *etree.Document
		menus *etree.Element
	}
)

func New() (xmlcurl.XmlConf, error) {
	xml := &Xml{
		doc: etree.NewDocument(),
	}
	/* 属性值不转译 */
	xml.doc.WriteSettings.CanonicalAttrVal = true
	xml.doc.CreateProcInst("xml", `version="1.0" encoding="UTF-8"`)
	document := xml.doc.CreateElement("document")
	document.CreateAttr("type", "freeswitch/xml")

	section := document.CreateElement("section")
	section.CreateAttr("name", "configuration")

	configuration := section.CreateElement("configuration")
	configuration.CreateAttr("name", "ivr.conf")

	xml.menus = configuration.CreateElement("menus")
	return xml, nil
}

func (x *Xml) BodyElement() *etree.Element {
	return x.menus
}

func (x *Xml) MarshalToXml() ([]byte, error) {
	x.doc.Indent(1)
	return x.doc.WriteToBytes()
}

func (x *Xml) UnMarshalFromString(v string) error {
	if x.doc == nil {
		x.doc = etree.NewDocument()
		/* 属性值不转译 */
		x.doc.WriteSettings.CanonicalAttrVal = true
	}
	if err := x.doc.ReadFromString(v); err != nil {
		return err
	}

	menus := x.doc.FindElement("./document/section/configuration/menus")
	if menus == nil {
		return errors.New("the document/section/configuration/menus is nil")
	}
	x.menus = menus
	return nil
}

func (x *Xml) WriteToFile(path string) error {
	x.doc.Indent(1)
	return x.doc.WriteToFile(path)
}
